import datetime
import time

import pandas as pd
from hs_udata import set_token, stock_quote_minutes, stock_quote_daily_list, fut_quote_minute

set_token(token='ruXPpxAnX4-5DOF7SXgKOuI4y7WOtBPVXqE79Nj2q30dHluNv6Hd-ylE-JwynvBZ')
startDate = "2022-01-01"
endDate = "2022-01-01"
userList = []
stockList = []
futuresList = []
openEntrustInfo = False
openAutoEntrust = True


def dayNum(day1, day2):
    time_array1 = time.strptime(day1, "%Y-%m-%d")
    timestamp_day1 = int(time.mktime(time_array1))
    time_array2 = time.strptime(day2, "%Y-%m-%d")
    timestamp_day2 = int(time.mktime(time_array2))
    result = (timestamp_day2 - timestamp_day1) // 60 // 60 // 24
    return result


def getMinDate(prod_code, nowDay):
    data = stock_quote_minutes(en_prod_code=str(prod_code),
                               begin_date=str(nowDay), end_date=str(nowDay))
    return data


def getFuturesData(code, start, end):
    data = fut_quote_minute(en_prod_code=code
                            , begin_date=str(start), end_date=str(end))
    data.rename(columns={'date': 'date'}, inplace=True)
    data.rename(columns={'time': 'time'}, inplace=True)
    data.rename(columns={'open': 'open'}, inplace=True)
    data.rename(columns={'high': 'high'}, inplace=True)
    data.rename(columns={'low': 'low'}, inplace=True)
    data.rename(columns={'close': 'close'}, inplace=True)
    data.rename(columns={'turnover_value': 'value'}, inplace=True)
    data.rename(columns={'turnover_volume': 'volume'}, inplace=True)
    data.drop(['amount', 'change_pct', 'change'], axis=1)
    return data


def getDayData(prod_code, start, end):
    data = stock_quote_daily_list(en_prod_code=str(prod_code), begin_date=str(start),
                                  end_date=str(end), adjust_way='1')

    data.sort_index(ascending=False, inplace=True)  # 设置排序
    data = data.reset_index(drop=True)
    return data


class HoldingStock:
    stock = ""
    num = 0
    lockNum = 0.0
    buyPrice = 0.0  # 买入单价
    buyAllPrice = 0.0  # 买入总价
    profit = 0.0  # 利润
    profitRatio = 0.0  # 利润率

    def __init__(self, stock, num, buyPrice):
        self.stock = stock
        self.num = num
        self.buyPrice = buyPrice

    def reload(self):
        self.profit = (self.stock.nowPrice - self.buyPrice) * self.num
        self.buyAllPrice = self.buyPrice * self.num
        self.profitRatio = self.profit / self.buyAllPrice

    def addNum(self, num, price):
        if num == 0:
            return
        self.buyPrice = (price + self.buyPrice) / 2
        self.num += num


class HoldingFutures:
    futures = ""
    case = 1  # 1涨 -1跌
    pry = 1  # 买入杠杆
    num = 0  # 持有数量
    buyPrice = 0.0  # 买入单价
    buyAllPrice = 0.0  # 买入总价
    value = 1.0  # 目前价值 剩余价值
    profit = 0.0  # 利润
    profitRatio = 0.0  # 利润率

    lockNum = 0.0

    def __init__(self, futures, num, buyPrice, case, pry):
        self.futures = futures
        self.case = case
        self.buyPrice = buyPrice
        self.pry = pry
        self.num = num

        self.value = buyPrice * num
        self.buyAllPrice = buyPrice * num

    def reload(self):
        self.buyAllPrice = self.buyPrice * (self.num + self.lockNum)
        if self.value > 0:
            self.profit = (self.futures.nowPrice - self.buyPrice) / \
                          self.buyPrice * self.case * self.buyAllPrice * self.pry  # 计算涨幅
            self.profitRatio = self.profit / self.buyAllPrice  # 涨幅比
            self.value = self.buyAllPrice + self.profit  # 目前价值

            if self.value <= 0:  # 亏不超过本金
                self.profit = -self.buyAllPrice
                self.value = 0
                self.profitRatio = -1
            return

        self.profit = -self.buyAllPrice
        self.value = 0


class EntrustStock:
    stock = ""
    num = 0
    price = 0

    def __init__(self, stock, num, price):
        self.stock = stock
        self.num = num
        self.price = price


class EntrustFutures:
    futures = ""
    num = 0
    price = 0
    case = 1
    pry = 1

    def __init__(self, futures, num, price, case, pry):
        self.futures = futures
        self.num = num
        self.price = price
        self.case = case
        self.pry = pry


class User:
    money = 0.0
    lockMoney = 0.0
    allMoney = 0.0
    holdingStockList = []
    holdingFuturesList = []
    entrustBuyList = []
    entrustSellList = []

    def __init__(self, money=10000):
        self.money = money
        self.allMoney = money
        global userList
        userList.append(self)

    def addEntrust(self, stockOrFutures, num, price, entrustType, case=1, pry=1):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            if entrustType == "buy":
                self.entrustBuyList.append(EntrustStock(stock, num, price))
                self.lockMoney += price * num  # 设置冻结资产
                self.money -= price * num  # 设置用户金额
                self.reloadAllMoney()  # 设置用户总资产
            if entrustType == "sell":
                self.entrustSellList.append(EntrustStock(stock, num, price))
                for holding in self.holdingStockList:  # 冻结股票
                    holding.lockNum += num  # 添加冻结股票数量
                    holding.num -= num  # 设置可操作股票数量

        if type(stockOrFutures) == Futures:
            futures = stockOrFutures
            if entrustType == "buy":
                self.entrustBuyList.append(EntrustFutures(futures, num, price, case, pry))
                self.lockMoney += price * num  # 设置冻结资产
                self.money -= price * num  # 设置用户金额
                self.reloadAllMoney()  # 设置用户总资产
            if entrustType == "sell":
                self.entrustSellList.append(EntrustFutures(futures, num, price, case, pry))
                for holding in self.holdingFuturesList:  # 冻结股票
                    if holding.num < num:  # 如果删除的数量超过当前仓的数量
                        if holding.num > 0:  # 并且有可操作
                            holding.lockNum += holding.num
                            holding.num = 0
                            num -= holding.num
                        continue
                    holding.lockNum += num  # 添加冻结股票数量
                    holding.num -= num  # 设置可操作股票数量
                    return

    def delEntrust(self, stockOrFutures, num, price, entrustType, case=1, pry=1):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            if entrustType == "buy":
                for entrust in self.entrustBuyList:
                    if entrust.stock == stock and entrust.num == num and entrust.price == price:
                        self.entrustBuyList.remove(entrust)
                        return "删除出售委托成功"
            if entrustType == "sell":
                for entrust in self.entrustSellList:
                    if entrust.stock == stock and entrust.num == num and entrust.price == price:
                        self.entrustSellList.remove(entrust)
                        return "删除购买委托成功"
        if type(stockOrFutures) == Futures:
            futures = stockOrFutures
            if entrustType == "buy":
                for entrust in self.entrustBuyList:
                    if entrust.futures == futures and entrust.num == num and entrust.price == price \
                            and entrust.case == case and entrust.pry == pry:
                        self.entrustBuyList.remove(entrust)
                        return "删除出售委托成功"
            if entrustType == "sell":
                for entrust in self.entrustSellList:
                    if entrust.futures == futures and entrust.num == num and entrust.price == price \
                            and entrust.case == case and entrust.pry == pry:
                        self.entrustSellList.remove(entrust)
                        return "删除购买委托成功"
        return "找不到该委托"

    def _addHolding(self, stockOrFutures, num, buyPrice, case=1, pry=1):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            for holding in self.holdingStockList:
                if holding.stock == stock:
                    holding.addNum(num, stock.nowPrice)
                    return
            self.holdingStockList.append(HoldingStock(stock, num, buyPrice))
        if type(stockOrFutures) == Futures:
            futures = stockOrFutures
            self.holdingFuturesList.append(HoldingFutures(futures, num, buyPrice, case, pry))

    def _delHolding(self, stockOrFutures, num, case=1, pry=1, isEntrust=False):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            for holding in self.holdingStockList:
                if holding.stock == stock:
                    if isEntrust:
                        holding.lockNum -= num

                        return
                    holding.num -= num
                    if holding.num + holding.lockNum == 0:
                        self.holdingStockList.remove(holding)
                    return
        if type(stockOrFutures) == Futures:
            futures = stockOrFutures
            for holding in self.holdingFuturesList:
                if holding.futures == futures and holding.case == case and holding.pry == pry:
                    if isEntrust:
                        holding.lockNum -= num
                        num = num - holding.lockNum
                    else:
                        holding.num -= num
                        num = num - holding.lockNum
                    if holding.lockNum + holding.num <= 0:
                        self.holdingFuturesList.remove(holding)
                    if num < 0:  # 当前的卖完了 继续往下卖
                        self.holdingFuturesList.remove(holding)
                        self._delHolding(stockOrFutures, -num, case=case, isEntrust=isEntrust)
                    return

    def reloadAllMoney(self):
        self.allMoney = 0  # 重置总资产
        for stock in stockList:  # 遍历所有股票
            for holding in self.holdingStockList:  # 获取所有持股
                if holding.stock == stock:  # 获取持股代码 与 股票代码 相同
                    self.allMoney += (holding.num + holding.lockNum) * stock.nowPrice  # 计算该持股的价值
        self.allMoney += self.money + self.lockMoney  # 将冻结资产加上
        for holding in self.holdingFuturesList:
            holding.reload()
            self.allMoney += holding.value

    def startEntrust(self):

        for entrustBuy in self.entrustBuyList:
            if type(entrustBuy) == EntrustStock:
                if entrustBuy.price >= entrustBuy.stock.nowPrice:  # 委托生效
                    self.lockMoney -= (entrustBuy.num * entrustBuy.price)  # 移除冻结资金
                    self._addHolding(entrustBuy.stock, entrustBuy.num, entrustBuy.price)
                    if openEntrustInfo:
                        print("委托已购入 股票" + str(entrustBuy.stock.code) +
                              " 数量:" + str(entrustBuy.num) +
                              " 价格:" + str(entrustBuy.price))
                    self.entrustBuyList.remove(entrustBuy)  # 删除委托

            if type(entrustBuy) == EntrustFutures:
                if entrustBuy.price >= entrustBuy.futures.nowPrice and entrustBuy.case == 1:  # 委托生效
                    self.lockMoney -= (entrustBuy.num * entrustBuy.price)  # 移除冻结资金
                    self._addHolding(entrustBuy.futures, entrustBuy.num, entrustBuy.price)
                    if openEntrustInfo:
                        print("委托已买多 期货" + str(entrustBuy.futures.code) + " 数量:" + str(
                            entrustBuy.num) + " 价格:" + str(
                            entrustBuy.price))
                if entrustBuy.price <= entrustBuy.futures.nowPrice and entrustBuy.case == -1:  # 委托生效
                    self.lockMoney -= (entrustBuy.num * entrustBuy.price)  # 移除冻结资金
                    self._addHolding(entrustBuy.futures, entrustBuy.num, entrustBuy.price)
                    if openEntrustInfo:
                        print("委托已卖空 期货" + str(entrustBuy.futures.code) + " 数量:" + str(
                            entrustBuy.num) + " 价格:" + str(
                            entrustBuy.price))

                self.entrustBuyList.remove(entrustBuy)  # 删除委托

        for entrustSell in self.entrustSellList:

            if type(entrustSell) == EntrustStock:
                if entrustSell.price <= entrustSell.stock.nowPrice:  # 委托生效
                    self.money += entrustSell.price * entrustSell.num  # 设置用户金额
                    self._delHolding(entrustSell.stock, entrustSell.num, isEntrust=True)  # 设置用户持股
                    self.reloadAllMoney()  # 设置用户总资产

                    if openEntrustInfo:
                        print("委托已出售 股票" +
                              str(entrustSell.stock.code) +
                              " 数量:" + str(entrustSell.num) +
                              " 价格:" + str(entrustSell.price))
                    self.entrustSellList.remove(entrustSell)  # 删除委托

            if type(entrustSell) == EntrustFutures:
                if entrustSell.price <= entrustSell.futures.nowPrice:  # 委托生效
                    self.money += entrustSell.price * entrustSell.num  # 设置用户金额
                    self._delHolding(entrustSell.futures, entrustSell.num, case=entrustSell.case, isEntrust=True)
                    if openEntrustInfo:
                        print("委托已出售 期货" + str(entrustSell.futures.code) +
                              " 数量:" + str(entrustSell.num) +
                              " 价格:" + str(entrustSell.price))
                    self.entrustSellList.remove(entrustSell)  # 删除委托

        self.reloadAllMoney()  # 设置用户总资产

    def put(self):
        self.reloadAllMoney()

        print("钱包:", '%.3f' % self.money,
              " 冻结:", '%.3f' % self.lockMoney,
              " 总资产:", '%.3f' % self.allMoney)

        print("持股:")
        for var in self.holdingStockList:
            var.reload()
            if len(self.entrustBuyList) == 0 and len(self.entrustSellList) == 0:
                print(" 股号:", var.stock.code,
                      " 数量:", var.num,
                      " 买入单价:", var.buyPrice,
                      " 买入总价", '%.3f' % var.buyAllPrice,
                      " 盈利:", '%.3f' % var.profit,
                      " 利润率:", '%.3f' % var.profitRatio)
            else:
                print(" 股号:", var.stock.code,
                      " 数量:", var.num,
                      " 冻结:", var.lockNum,
                      " 买入单价:", var.buyPrice,
                      " 买入总价", '%.3f' % var.buyAllPrice,
                      " 盈利:", '%.3f' % var.profit,
                      " 利润率:", '%.3f' % var.profitRatio)
        print("期货:")
        for var in self.holdingFuturesList:

            var.reload()
            if var.case == -1:
                print(" 【卖空】 代号:", var.futures.code,
                      " 可用数量:", var.num,
                      " 冻结数量:", var.lockNum,
                      " 买入价格", '%.3f' % var.buyAllPrice,
                      " 目前价值:", '%.3f' % var.value,
                      " 利润:", '%.3f' % var.profit,
                      " 利润率", '%.3f' % var.profitRatio,
                      " 杠杆:", var.pry)
            if var.case == 1:
                print(" 【买多】 代号:", var.futures.code,
                      " 可用数量:", var.num,
                      " 冻结数量:", var.lockNum,
                      " 买入价格", '%.3f' % var.buyAllPrice,
                      " 目前价值:", '%.3f' % var.value,
                      " 利润:", '%.3f' % var.profit,
                      " 利润率", '%.3f' % var.profitRatio,
                      " 杠杆:", var.pry)

        print("委托:")
        for var in self.entrustBuyList:
            if type(var) == EntrustStock:
                print("购买  股号:", var.stock.code,
                      "  数量:", var.num,
                      "  价格:", var.price)
            if type(var) == EntrustFutures:
                if var.case == 1:
                    print("买多  股号:", var.futures.code,
                          "  数量:", var.num,
                          "  单价:", var.price)
                if var.case == -1:
                    print("卖空  股号:", var.futures.code,
                          "  数量:", var.num,
                          "  单价:", var.price)
        for var in self.entrustSellList:
            if type(var) == EntrustStock:
                print("出售  股号:", var.stock.code,
                      "  数量:", var.num,
                      "  价格:", var.price)
            if type(var) == EntrustFutures:
                if var.case == 1:
                    print("平仓买多  股号:", var.futures.code,
                          "  数量:", var.num,
                          "  单价:", var.price)
                if var.case == -1:
                    print("平仓卖空  股号:", var.futures.code,
                          "  数量:", var.num,
                          "  单价:", var.price)

    def getHoldingStock(self, stock):
        for holding in self.holdingStockList:
            if holding.code == stock.code:
                return holding
        return None

    def buy(self, stockOrFutures, num, price, autoEntrust=False, case=1, pry=1):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            if self.money < price * num:
                return "金额不足"
            if price >= stock.nowPrice:  # 判断是否购买成功
                self.money -= price * num  # 设置用户金额
                self._addHolding(stock, num, price)  # 设置用户持股
                self.reloadAllMoney()  # 设置用户总资产
                return '成功购入 股票:' + str(stock.code) + ' 数量:' + str(num) + ' 价格:' + str(price)
            elif autoEntrust:
                self.addEntrust(stock, num, price, "buy")  # 添加购买委托
                return "已添加购买委托"
            else:
                return "购入失败"

        if type(stockOrFutures) == Futures:
            futures = stockOrFutures

            if price == 0:
                return "请输入买入单价"
            if self.money < price * num:
                return "金额不足"

            if price < futures.nowPrice and case == 1:
                if autoEntrust:
                    self.addEntrust(futures, num, price, "buy", case=case, pry=pry)  # 添加购买委托
                    return "已添加建仓委托"
                return "买入失败"
            if price > futures.nowPrice and case == -1:
                if autoEntrust:
                    self.addEntrust(futures, num, price, "buy", case=case, pry=pry)  # 添加购买委托
                    return "已添加建仓委托"
                return "建仓失败"

            self._addHolding(futures, num, price, case=case, pry=pry)
            self.money -= price * num
            self.reloadAllMoney()  # 设置用户总资产
            if case == 1:
                return '买多 代号:' + str(futures.code) + "  单价:" + str(price) + "  杠杆:" + str(pry)
            if case == -1:
                return '卖空 代号:' + str(futures.code) + "  单价:" + str(price) + "  杠杆:" + str(pry)

    def sell(self, stockOrFutures, num, price, autoEntrust=False, case=1, pry=1):
        if type(stockOrFutures) == Stock:
            stock = stockOrFutures
            for holding in self.holdingStockList:
                if holding.stock == stock and holding.num < num:
                    return "你没有那么多持股"
            if price <= stock.nowPrice:
                self.money += price * num  # 设置用户金额
                self._delHolding(stock, num)  # 设置用户持股
                self.reloadAllMoney()  # 设置用户总资产
                return "已出售 股票" + str(stock.code) + " 数量:" + str(num) + " 价格:" + str(price)
            elif autoEntrust:
                self.addEntrust(stock, num, price, "sell")
                return "已添加出售委托"
            else:
                return "出售失败"
        if type(stockOrFutures) == Futures:
            futures = stockOrFutures
            holdingAllNum = 0
            for holding in self.holdingFuturesList:
                if holding.futures == futures and holding.case == case and holding.pry == pry:
                    holdingAllNum += holding.num
            if holdingAllNum < num:
                return "你没有持有那么多"

            if price > futures.nowPrice and case == 1:
                if autoEntrust:
                    self.addEntrust(futures, num, price, "sell", case=case, pry=pry)
                    return "已添加出售委托"
                return "卖出失败"
            if price < futures.nowPrice and case == -1:
                if autoEntrust:
                    self.addEntrust(futures, num, price, "sell", case=case, pry=pry)
                    return "已添加出售委托"
                return "卖出失败"

            self.money += price * num  # 设置用户金额
            self._delHolding(futures, num, case=case, pry=pry)  # 删除用户持股
            self.reloadAllMoney()  # 设置用户总资产

            if case == 1:
                return "已平仓 买多 期货" + str(futures.code) + " 数量:" + str(num) + " 单价:" + str(price)
            if case == -1:
                return "已平仓 卖空 期货" + str(futures.code) + " 数量:" + str(num) + " 单价:" + str(price)


class Futures:
    code = ""
    nowPrice = 0.0

    oldDayData = pd.DataFrame({})  # 历史日数据 多
    oldMinData = pd.DataFrame({})  # 历史分钟数据 多

    nowMinData = pd.DataFrame({})  # 最新分钟数据 单
    nowDayData = pd.DataFrame({})  # 最新日数据 单

    nowData = pd.DataFrame({})  # 当前数据 单

    futureAllMinData = pd.DataFrame({})  # 未来所有分钟数据
    futureDayData = pd.DataFrame({})  # 未来日数据
    toDayFutureMinData = pd.DataFrame({})  # 当天未来分钟数据
    toDayOldMinData = pd.DataFrame({})
    nowDate = 0

    def __init__(self, code):

        global futuresList
        self.code = code
        self.getAllData()
        futuresList.append(self)

    def getAllData(self):
        end = datetime.datetime.strptime(startDate, '%Y-%m-%d')
        end = end - datetime.timedelta(days=1)  # 获取到开始前一天
        start = end - datetime.timedelta(days=30)  # 设置结束在开始前200天的日期
        self.oldMinData = getFuturesData(self.code, start, end)  # 获取历史股价
        self.nowPrice = float(self.oldMinData.open.values[-1])  # 设置最新价格

        self.futureAllMinData = getFuturesData(self.code, startDate, endDate)  # 获取未来数据
        self.getOldDayData()
        self.getFutureDayData()

    def getOldDayData(self):  # 计算历史日数据
        start = self.oldMinData.date.values[0]
        end = self.oldMinData.date.values[-1]
        date = datetime.datetime.strptime(start, '%Y-%m-%d')
        for day in range(0, dayNum(start, end) + 1):
            dayData = self.oldMinData[self.oldMinData["date"] == str(date.date())]
            dayData = dayData.reset_index(drop=True)
            date += datetime.timedelta(days=1)  # 下一天
            if len(dayData) == 0:
                continue
            newDataFrame = {'date': dayData.date.values[0],
                            'open': dayData.open.values[0],
                            'high': dayData.high.max(),
                            'low': dayData.low.min(),
                            'close': dayData.close.values[-1],
                            'volume': dayData.volume.sum(),
                            'value': dayData.value.sum(),
                            }

            newDataFrame = pd.DataFrame(newDataFrame, index=[0])
            self.oldDayData = pd.concat([self.oldDayData, newDataFrame], ignore_index=True)

    def getFutureDayData(self):  # 计算未来日数据
        start = self.futureAllMinData.date.values[0]
        end = self.futureAllMinData.date.values[-1]
        date = datetime.datetime.strptime(start, '%Y-%m-%d')
        for day in range(0, dayNum(start, end) + 1):
            dayData = self.futureAllMinData[self.futureAllMinData["date"] == str(date.date())]
            dayData = dayData.reset_index(drop=True)
            date += datetime.timedelta(days=1)  # 下一天
            if len(dayData) == 0:
                continue
            newDataFrame = {'date': dayData.date.values[0],
                            'open': dayData.open.values[0],
                            'high': dayData.high.max(),
                            'low': dayData.low.min(),
                            'close': dayData.close.values[-1],
                            'volume': dayData.volume.sum(),
                            'value': dayData.value.sum(),
                            }

            newDataFrame = pd.DataFrame(newDataFrame, index=[0])
            self.futureDayData = pd.concat([self.futureDayData, newDataFrame], ignore_index=True)

    def nextDay(self):  # 下一日
        for user in userList:
            user.reloadAllMoney()
        if len(futuresList) == 0:  # 期货为空
            return False
        if len(self.futureDayData) == 0:  # 是否遍历完未来
            return False

        for user in userList:
            user.startEntrust()  # 执行委托

        self.oldDayData = pd.concat([self.oldDayData, self.futureDayData[0:1]], ignore_index=True)
        self.futureDayData = self.futureDayData[1:]
        self.nowDayData = self.oldDayData[-1:]  # 设置当前日数据
        self.nowPrice = float(self.oldDayData.close.values[-1])  # 设置最新价格
        self.nowDate = self.oldDayData.date.values[-1]  # 更新日期
        self.toDayFutureMinData = self.futureAllMinData[self.futureAllMinData["date"] == self.nowDate]  # 设置当天的所有分钟数据

        for user in userList:
            user.startEntrust()  # 执行委托

        return True

    def nextMin(self):

        if len(futuresList) == 0:  # 期货为空
            return False
        if len(self.toDayFutureMinData) == 0:  # 是否遍历完当日未来
            return False

        for user in userList:
            user.reloadAllMoney()
            user.startEntrust()  # 执行委托

        self.oldMinData = pd.concat([self.oldMinData, self.toDayFutureMinData[0:1]], ignore_index=True)

        self.nowPrice = self.oldMinData.close.values[-1]
        self.toDayFutureMinData = self.toDayFutureMinData[1:]
        self.toDayFutureMinData = self.toDayFutureMinData.reset_index(drop=True)  # 设置排序

        self.nowMinData = self.oldMinData[-1:]  # 设置当前分钟数据

        for user in userList:
            user.startEntrust()  # 执行委托

        return True


class Stock:
    code = ""
    nowPrice = 0.0

    oldMinData = pd.DataFrame({})
    oldDayData = pd.DataFrame({})
    nowDayData = pd.DataFrame({})
    nowMinData = pd.DataFrame({})

    futureMinData = pd.DataFrame({})
    futureDayData = pd.DataFrame({})

    def __init__(self, code):
        self.code = code
        self.getAllData()  # 获取旧信息
        global stockList
        stockList.append(self)

    def getAllData(self):
        end = datetime.datetime.strptime(startDate, "%Y-%m-%d") - datetime.timedelta(days=1)  # 获取到开始前一天
        start = end - datetime.timedelta(days=200)  # 设置结束在开始前200天的日期
        self.oldDayData = getDayData(self.code, start, end)  # 获取历史股价
        self.nowPrice = float(self.oldDayData.open_price.values[-1])  # 设置最新价格

        self.futureDayData = getDayData(self.code, startDate, endDate)  # 获取未来数据

    def nextDay(self):  # 下一日
        if len(stockList) == 0:
            return
        if len(self.futureDayData) == 0:
            return
        for user in userList:
            user.startEntrust()  # 执行委托

        self.oldDayData = pd.concat([self.oldDayData, self.futureDayData[0:1]], ignore_index=True)  # 将未来数据第一行添加到历史数据
        self.futureDayData = self.futureDayData[1:]  # 未来数据往后移
        self.nowDayData = self.oldDayData[-1:]
        self.nowPrice = float(self.oldDayData.open_price.values[-1])  # 设置最新价格

        self.futureMinData = getMinDate(self.code, self.oldDayData.trading_date.values[-1])  # 更新完日后 获取当日分钟数据

        for user in userList:
            user.startEntrust()

        return True

    def nextMin(self):

        if len(stockList) == 0:
            return False
        if len(self.futureMinData) == 0:
            return False

        for user in userList:
            user.startEntrust()  # 执行委托

        self.oldMinData = pd.concat([self.oldMinData, self.futureMinData[0:1]], ignore_index=True)
        self.futureMinData = self.futureMinData[1:]
        self.nowMinData = self.oldMinData[-1:]
        self.nowPrice = float(self.oldMinData.open.values[-1])

        for user in userList:
            user.startEntrust()
        return True

    def getTodayData(self):
        return self.oldDayData[-1]

    def getNowMin(self):
        return len(self.oldMinData)


def nextDay():
    var1 = False
    var2 = False
    for stock in stockList:  # 遍历选股列表
        var1 = stock.nextDay()  # 更新股票最新数据
    for futures in futuresList:
        var2 = futures.nextDay()

    return var1 or var2


def nextMin():
    var1 = False
    var2 = False
    for stock in stockList:
        var1 = stock.nextMin()  # 获取实时分钟数据
    for futures in futuresList:
        var2 = futures.nextMin()  # 遍历当日分钟完返回False

    return var1 or var2


def config(startDate_, endDate_):
    global startDate, endDate
    startDate = startDate_
    endDate = endDate_
